import re

from django import template

from ftbexplorer.core.models import Sentence, TreeNode

register = template.Library()

@register.filter
def normalize_punctuation(text):
    text = re.sub(r'([-\'\(])\s+', r'\1', text)
    text = re.sub(r'\s+([-.,\'\)])', r'\1', text)
    return text
    

@register.filter
def highlight(text, string):
    text = re.sub(r'(%s)' % string, r'<span class="highlighted">\1</span>', text)
    text = re.sub(r'\s+([-.,\'\)])', r'\1', text)
    return text
    
def bracket_tree(tree):
    assert isinstance(tree, TreeNode)
    if not tree.is_word():
        #return unicode(tree.children())
        #print map(unicode, tree.children())
        inside = map(bracket_tree, tree.children())
        return u"<span class=\"phrase\">%s</span><span class=\"tag\">%s</span>" % (
            u" ".join(inside),
            tree.nodeName)
    else:
        return tree.wordtreenode.form

@register.filter
def bracket(sent):
    assert isinstance(sent, Sentence)
    tree = bracket_tree(sent.tree)
    return u"<span class=\"bracketed_tree\">%s</span>" % tree
